const Storage = require('../../utils/storage')

Page({
  data: {
    addresses: []
  },

  onLoad() {
    this.loadAddresses()
  },

  onShow() {
    this.loadAddresses()
  },

  // 加载地址列表
  loadAddresses() {
    const addresses = Storage.getAddresses()
    this.setData({ addresses })
  },

  // 添加新地址
  addAddress() {
    wx.chooseAddress({
      success: (res) => {
        const address = {
          id: Date.now(),
          name: res.userName,
          phone: res.telNumber,
          province: res.provinceName,
          city: res.cityName,
          district: res.countyName,
          detail: res.detailInfo,
          isDefault: this.data.addresses.length === 0
        }

        const addresses = [address, ...this.data.addresses]
        Storage.setAddresses(addresses)
        this.setData({ addresses })

        wx.showToast({
          title: '添加成功',
          icon: 'success'
        })
      },
      fail: (err) => {
        console.error('获取收货地址失败', err)
        wx.showToast({
          title: '获取地址失败',
          icon: 'none'
        })
      }
    })
  },

  // 删除地址
  deleteAddress(e) {
    const { id } = e.currentTarget.dataset
    wx.showModal({
      title: '提示',
      content: '确定要删除这个地址吗？',
      success: (res) => {
        if (res.confirm) {
          const addresses = this.data.addresses.filter(addr => addr.id !== id)
          Storage.setAddresses(addresses)
          this.setData({ addresses })
          
          wx.showToast({
            title: '删除成功',
            icon: 'success'
          })
        }
      }
    })
  },

  // 设为默认地址
  setDefault(e) {
    const { id } = e.currentTarget.dataset
    const addresses = this.data.addresses.map(addr => ({
      ...addr,
      isDefault: addr.id === id
    }))
    Storage.setAddresses(addresses)
    this.setData({ addresses })

    wx.showToast({
      title: '设置成功',
      icon: 'success'
    })
  }
}) 